/* 消息通知模块使用，主要与socket相关 */
import Vue from "vue";
import Axios from "axios"; // Axios
import Api from "@/api";
import User from "./user.js";

const state = {
  socket: "",

  list: [],
  clock: ""
};

const mutations = {
  /* 暂存socket对象 */
  SET_SOCKET: ( state, socket ) => { state.socket = socket; },

  /* 暂存notice轮询对象 */
  SET_MESSAGE_CLOCK: ( state, clock ) => { state.messageClock = clock; },
  /* 保存未读消息 */
  SET_MESSAGELIST: (state, list) => { state.messageList = list; },

  /* 暂存notice轮询对象 */
  SET_NOTICE_CLOCK: ( state, clock ) => { state.noticeClock = clock; },
  /* 保存未读消息 */
  SET_NOTICELIST: (state, list) => { state.noticeList = list; }
};

const actions = {
  startSocket ({ commit, dispatch, state }) {
    if (state.socket) return;

    /* 初始化 */
    const socket = io(SETTING.socket + "/notice");
    socket.connect();
    // 打开消息监听事件
    socket.on("ToNotice", r => {
      const res = eval( "(" + r + ")" );
      const matchUser = res["user_codes"].find(i => {
        return i === User.state.userInfo["user_code"];
      });
      if (matchUser) {
        dispatch("getNotice");
        dispatch("getMessage");
      }
    });
    commit("SET_SOCKET", socket);
    dispatch("getNotice");
    dispatch("getMessage");
  },

  /* 手动触发的获取未读通知 */
  async getNotice ({ commit, state }) {
    await Axios.post(Api.GET_NOTICE_UNREAD, {}, { dropLoading: true }).then(res => {
      commit("SET_NOTICELIST", res.data);
    });
  },
  /* 手动触发的获取未读消息 */
  async getMessage ({ commit, state }) {
    await Axios.post(Api.GET_MESSAGE_UNREAD, {}, { dropLoading: true }).then(res => {
      commit("SET_MESSAGELIST", res.data);
    });
  },

  /* 清空socket */
  destroySocket ({commit, state}) {
    state.socket.removeAllListeners(["ToClient"]);
    state.socket.disconnect(true);
    state.socket.close();
    commit("SET_SOCKET", "");
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
